﻿using Catalogo.Portable.DataSources;
using Catalogo.Portable.ViewModel;
using Catalogo.Windows8.Common;
using Catalogo.Windows8.Views;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media.Animation;

namespace Catalogo.Windows8
{
    sealed partial class App : Application
    {
        double settingsWidth = 370;
        Popup settingsPopup;

        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            await CatalogoDataSource.Instance.LoadAsync();

            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Activate();
                return;
            }

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                try
                {
                    await SuspensionManager.RestoreAsync();
                }
                catch (SuspensionManagerException)
                {
                }
            }

            var rootFrame = new Frame();
            if (!rootFrame.Navigate(typeof(HomePage)))
            {
                throw new Exception("Falhou ao criar a página inicial");
            }

            Window.Current.Content = rootFrame;
            Window.Current.Activate();

            await EnableLiveTile.CreateLiveTile.ShowLiveTileAsync();
        }

        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
        }

        void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler(onSettingsCommand);

            SettingsCommand aboutCommand = new SettingsCommand("AU", "Sobre", handler);
            args.Request.ApplicationCommands.Add(aboutCommand);

            SettingsCommand contactCommand = new SettingsCommand("CU", "Contato", handler);
            args.Request.ApplicationCommands.Add(contactCommand);

            SettingsCommand privacyCommand = new SettingsCommand("PP", "Política de privacidade", handler);
            args.Request.ApplicationCommands.Add(privacyCommand);
        }

        private void onSettingsCommand(IUICommand command)
        {
            Rect windowBounds = Window.Current.Bounds;
            settingsPopup = new Popup();

            settingsPopup.Closed += settingsPopup_Closed;
            Window.Current.Activated += Current_Activated;
            settingsPopup.IsLightDismissEnabled = true;
            Page settingPage = null;

            switch (command.Id.ToString())
            {
                case "AU":
                    settingPage = new FlyoutTexto(TipoFlyoutTexto.Sobre);
                    break;
                case "CU":
                    settingPage = new FlyoutTexto(TipoFlyoutTexto.Contato);
                    break;
                case "PP":
                    settingPage = new FlyoutTexto(TipoFlyoutTexto.PoliticaPrivacidade);
                    break;
            }

            settingsPopup.Width = settingsWidth;
            settingsPopup.Height = windowBounds.Height;

            settingsPopup.ChildTransitions = new TransitionCollection();

            settingsPopup.ChildTransitions.Add(new PaneThemeTransition()
            {

                Edge = (SettingsPane.Edge == SettingsEdgeLocation.Right) ?
                EdgeTransitionLocation.Right :
                EdgeTransitionLocation.Left
            });

            if (settingPage != null)
            {
                settingPage.Width = settingsWidth;
                settingPage.Height = windowBounds.Height;
            }

            settingsPopup.Child = settingPage;

            settingsPopup.SetValue(Canvas.LeftProperty, SettingsPane.Edge == SettingsEdgeLocation.Right ? (windowBounds.Width - settingsWidth) : 0);
            settingsPopup.SetValue(Canvas.TopProperty, 0);
            settingsPopup.IsOpen = true;
        }

        void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
            {
                settingsPopup.IsOpen = false;
            }
        }

        void settingsPopup_Closed(object sender, object e)
        {
            Window.Current.Activated -= Current_Activated;
        }

        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        protected async override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
        {
            await CatalogoDataSource.Instance.LoadAsync();

            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            if (frame == null)
            {
                frame = new Frame();
                SuspensionManager.RegisterFrame(frame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                    }
                }

                frame.Navigate(typeof(HomePage));
            }

            if (frame.CurrentSourcePageType == typeof(ResultadoBusca) && frame.CanGoBack)
            {
                frame.GoBack();
            }
            frame.Navigate(typeof(ResultadoBusca), args.QueryText);

            Window.Current.Content = frame;
            Window.Current.Activate();
        }
    }
}
